{% extends "base.html" %}
{% load i18n dv_filters bootstrap3 forms_utils %}

{% block head_title %}
  {% blocktrans trimmed with year=month.year month=month|date:'F' %}
    Heures pour {{ month }} {{ year }}
  {% endblocktrans %}
{% endblock %}
{% block container-class %}{% if dataset %}container-fluid{% else %}{{ block.super }}{% endif %}{% endblock %}

{% block bootstrap3_extra_script %}
  {{ formset.media.js }}
  {% include 'snippets/datetimepicker_js.html' %}
{% endblock %}

{% block content %}
{% include 'info/_month_nav.html' with nav_url=nav_url previous_url=prev_url previous_month=previous_month next_url=next_url next_month=next_month only %}

{% if monitor_name %}
<h1>{% blocktrans with name=monitor_name year=month.year month=month|date:'F' %}Heures de {{ name }} pour {{ month }} {{ year }}{% endblocktrans %}</h1>
{% else %}
<h1>{% blocktrans with year=month.year month=month|date:'F' %}Heures pour {{ month }} {{year}}{% endblocktrans %}</h1>
{% endif %}
{% if object_list %}
<form method="post">
  {% csrf_token %}
  {{ formset.management_form }}
  {% for form in formset.forms %}
    {% if form.non_field_errors %}
    <div class='row form-group'>
      <div class='{% firstof label_class "col-sm-4" %}'></div>
      <div class='{% firstof field_class "col-sm-8" %} alert alert-warning'>
        {{ form.non_field_errors }}
      </div>
    </div>
    {% endif %}
  {% endfor %}
  <table id="table-with-sum" class="table">
    <thead>
      <tr>
        <td></td>
        {% for form in formset.forms %}
        <th align="center" class="text-center{% if form.non_field_errors %} warning{% endif %}">
          {{ form.date.value }}
          {% for hidden in form.hidden_fields %}
          {{ hidden }}
          {% endfor %}
        </th>
        {% endfor %}
        <th rowspan="2" align="center" class="text-center">{% trans "Total" %}</th>
      </tr>
      <tr>
        <th>{% trans "Sessions" %}</th>
        {% for day, sessions in all_sessions_by_day.items %}
        <td align="left" class="text-left small">
          {% for session in sessions %}
              <a href="{% url 'session-detail' session.season.pk session.pk %}" target="_blank">{{ session.begin }} {{ session.orga.ifabbr }}</a><br />
          {% endfor %}
        </td>
        {% endfor %}
      </tr>
    </thead>

    <tbody>
      {% for label, fields in fields_grouped_by_field_name.items %}
      <tr class="{{ fields.0|field_type }}{% if not user|can:"timesheet_editor" and fields.0.name == 'ignore' %} readonly{% endif %}">
        <th>{{ label|capfirst }}</th>
        {% for field in fields %}
        <td align="center">
          {% bootstrap_field field layout="inline"  size='small' %}
        </td>
        {% endfor %}
        <td class="text-center"></td>
      </tr>
      {% endfor %}
    </tbody>
    <tfoot>
      <tr>
        <th>{% trans "Total heures"%}</th>
        {% for form in formset.forms %}
        <td align="center" class="text-center">
        </td>
        {% endfor %}
        <td class="text-center"></td>
      </tr>
      <tr>
        <th>
        {% trans "Total CHF"%} <br/>
        <small class="text-muted">{% trans "Attention : Ceci n’est pas le salaire net mais le décompte des heures et des indemmnités" %}</small>
        </th>
        {% for form in formset.forms %}
        <td align="center" class="text-center">
        </td>
        {% endfor %}
        <td class="text-center"></td>
      </tr>
    </tfoot>
  </table>
  {% buttons %}
  <div class="pull-right hidden-print">
    {% if can_print %}
    <a class="btn btn-default" title="{% blocktrans %}Imprimer{% endblocktrans %}" href="javascript:window.print()">
      <span class="glyphicon glyphicon-print" aria-hidden="true"></span>
    </a>
    {% endif %}
    <button type="submit" class="btn btn-primary">{% trans "Enregistrer" %}</button>
  </div>
  <a class="btn btn-default hidden-print" href="{% if return_url %}{{ return_url }}{% else %}{% url 'salary:timesheets-overview' year %}{% endif %}">{% trans "Annuler" %}</a>
  {% endbuttons %}
</form>
{% else %}
{% if in_the_future %}
  <p>{% trans "Vous ne pouvez pas entrer des heures dans le futur." %}</p>
{% elif is_current_month %}
  <p>{% trans "Vous n’avez pas encore d’heures à rentrer ce mois." %}</p>
{% else %}
  <p>{% trans "Vous n’avez pas travaillé ce mois." %}</p>
{% endif %}
{% endif %}

{% if orphaned_timesheets and request.user|can:"timesheet_editor" %}
<div class="panel panel-danger hidden-print">
  <div class="panel-heading">{% blocktrans with n=orphaned_timesheets|length %}Il y a {{n}} feuilles d'heure orphelines ce mois.{% endblocktrans %}</div>
  <div class="panel-body">
    <table class="table">
      <thead>
        <tr>
          <th>{% trans "Quand" %}</th>
          <th>{% trans "Heures moni·teur·trice" %}</th>
          <th>{% trans "Intervention(s)" %}</th>
          <th>{% trans "Participation(s) comme moniteur 2" %}</th>
          <th>{% trans "Heures supplémentaires" %}</th>
          <th>{% trans "Heures de trajet" %}</th>
          <th>{% trans "Validée" %}</th>
        </tr>
      </thead>
      <tbody>
        {% for timesheet in orphaned_timesheets %}
        <tr>
          <td>
            <a href="{% url 'salary:user-timesheets' year=timesheet.date.year month=timesheet.date.month pk=timesheet.user.pk %}">
              {{ timesheet.date }}
            </a>
          </td>
          <td>{{ timesheet.time_helper }}</td>
          <td>{{ timesheet.actor_count }}</td>
          <td>{{ timesheet.leader_count }}</td>
          <td>{{ timesheet.overtime }}</td>
          <td>{{ timesheet.traveltime }}</td>
          <td><span class="glyphicon glyphicon-{% if timesheet.validated_at %}check{% else %}unchecked{% endif %}"></span></td>
        </tr>
        {% endfor %}
      </tbody>
    </table>
    <a
      class="btn btn-default pull-right"
      href="{% url "salary:cleanup-timesheets" year=year month=month.month %}?canton={{ user.profile.affiliation_canton }}">
      {% blocktrans with n=orphaned_timesheets|length %}Examiner les entrées orphelines{% endblocktrans %}
    </a>
  </div>
</div>
{% endif %}

<script type="text/javascript">
  document.addEventListener("DOMContentLoaded", function (event) {
    const displayTime = function(value){
        const hours = Math.trunc(value);
        const minutes = (Math.abs(value) - Math.abs(hours)) * 60 % 60;
        return (value < 0 ? "-" : "" ) + Math.abs(hours) + ":" + ("0" + minutes).slice(-2);
    };
    $("tr.checkboxinput:not(.readonly)").each(function () {
      let link = $('<a href="#" class="btn btn-primary">{% trans "Tout sélectionner" %}</a>').click(function(e){
        e.preventDefault();
        $(this).closest('tr').find('input[type=checkbox]').each(function(){
          if (! $(this).prop('disabled')) {
            $(this).prop('checked', true);
          }
        });
        $("table#table-with-sum").change();
        return false;
      });
      $(this).find(' > td:last').append(link);
    });
    $("table#table-with-sum input").change(function(e){ $("table#table-with-sum").change()})
    $("table#table-with-sum").change(function (e) {
      $('table#table-with-sum > thead > tr > th:not(:last)').each(function (index) {
        var total = 0;
        var total_editables = 0;
        var sum_salary = 0;
        var ignore = false;
        $('table#table-with-sum > tbody > tr').each(function () {
          const input = $(this).children('td').eq(index).find("input[type=number]")
          let value = parseFloat(input.val());
          if (!isNaN(value)) {
            if (input.data("customType") == "hours") {
              total += value;
              if (input.attr("readonly") != "readonly") {
                total_editables += value;
              }
            }
            if (input.data("unitPrice")) {
              sum_salary += parseFloat(input.data("unitPrice")) * value;
            }
          }

          const checkbox = $(this).children("td").eq(index).find("input[type=checkbox]")
          if (checkbox.data("function") == "ignore" && checkbox.prop("checked")) {
              ignore = true;
          }
        });
        if (ignore) {
          total = 0;
          sum_salary = 0;
        }
        $('table#table-with-sum > tbody > tr > td textarea').eq(index).prop('required', total_editables != 0);
        $('table#table-with-sum > tfoot > tr:first > td').eq(index).data("floatValue", total).text(displayTime(total));
        $('table#table-with-sum > tfoot > tr:nth-child(2) > td').eq(index).data("floatValue", sum_salary)
          .text(sum_salary.toFixed(2))
      });
      $('table#table-with-sum > tbody > tr').each(function () {
        const sum = $(this).find("input[type=number]").get().reduce(function (total, input) {
          let value = parseFloat($(input).val());
          if (!isNaN(value)) {
            return (total || 0) + value;
          }
          return total;
        }, null);
        if (sum !== null) {
          if ($(this).find("input[type=number]").first().data("customType") == "hours") {
            $(this).find(' > td:last').text(displayTime(sum));
          } else {
            $(this).find(' > td:last').text(sum);
          }
        }

      });
      $('table#table-with-sum > tfoot > tr').each(function (index) {
        const sum = $(this).find("td:not(:last)").get().reduce(function (total, elem) {
          let value = parseFloat($(elem).data('floatValue'));
          if (!isNaN(value)) {
            return (total || 0) + value;
          }
          return total;
        }, null);
        if (index == 0){
            $(this).find(' > td:last').text(displayTime(sum));
        } else {
            $(this).find(' > td:last').text(sum.toFixed(2));
        }
      });
    }).change();
  });

</script>
{% endblock %}
